package com.sbr.esbmonitor.repositories.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//TODO renommer en JAXBManager
public class JAXBUtils {

	private static final Logger LOG = LoggerFactory.getLogger(JAXBUtils.class);
	
	@SuppressWarnings("unchecked")
	public <T> T unmarshal(String fileName) {
		JAXBContext context;
		T type = null;
		try {
			context = JAXBContext.newInstance("com.sbr.esbmonitor.model.xml.servers");
			Unmarshaller unMarshaller = context.createUnmarshaller();
			InputStream is = new FileInputStream(new File(fileName));
			type = (T) unMarshaller.unmarshal(is);
		} catch (JAXBException e) {
			LOG.error("Error lors du Unmarshalling",e);
		} catch (FileNotFoundException e) {
			LOG.error("Le fichier {} n'a pas &été trouvé",fileName,e);
		}
		return type;
	}
	
	public <T> void marshal(String fileName, T elements) {
		JAXBContext context;
		try {
			context = JAXBContext.newInstance("com.sbr.esbmonitor.model.xml.servers");
			Marshaller marshaller = context.createMarshaller();

			OutputStream os = new FileOutputStream(new File(fileName));
			marshaller.marshal(elements, os);
		} catch (JAXBException e) {
			LOG.error("Error lors du Marshalling",e);
		} catch (FileNotFoundException e) {
			LOG.error("Le fichier {} n'a pas &été trouvé",fileName,e);
		}
	}
}
